package org.deyang.tools.amazon;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.deyang.tools.amazon.exceptions.ImageFetchFailException;
import org.deyang.tools.amazon.services.ImageFormItem;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.urlfetch.FetchOptions.Builder;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

public class WeiboPostServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4208249225690161375L;
	private static final Logger log = Logger.getLogger(WeiboPostServlet.class.getName());
	private static String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";

	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		
		Query weiboq = new Query("AmazonProduct");
		weiboq.addFilter("asin", Query.FilterOperator.EQUAL, req.getParameter("asin"));
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		PreparedQuery pq = datastore.prepare(weiboq);
		Iterator<Entity> iter = pq.asIterator();
		 
		if (iter.hasNext()){
			Entity resultEntity = iter.next();
			byte[] file = null;
			String picContentType = null;
			try{
				ImageFormItem ifi = new ImageFormItem((String) resultEntity.getProperty("imgurl"));
				file = ifi.getImageData();
				picContentType = ifi.getImageContentType();
			} catch (ImageFetchFailException e1) {
				log.severe(e1.getMessage());
				resp.setStatus(400);
				return;
			}
			
			String urlStr = "";
			Object urlObject = resultEntity.getProperty("shorturl");
			if (urlObject instanceof Text){
				urlStr = ((Text)urlObject).getValue();
			}else{
				urlStr = (String)urlObject;
			}
			
			String weiboText = URLEncoder.encode("" + resultEntity.getProperty("amazonProductTitle") + ", 现仅" + resultEntity.getProperty("dealPrice") + " #海购# #海淘# " + urlStr, "UTF-8");
			URL weiboposturl = new URL("https://api.weibo.com/2/statuses/upload.json" );
			

			HTTPRequest request = new HTTPRequest(weiboposturl
			        , HTTPMethod.POST
			        , Builder.disallowTruncate().doNotValidateCertificate().setDeadline((double) 55)
			);
			
	        //Set header
	        //request.setHeader(new HTTPHeader("access_token", req.getParameter("token")));
			request.addHeader(new HTTPHeader("Authorization", "OAuth2 " + req.getParameter("token")));
	        request.addHeader(new HTTPHeader("Accept-Charset", "UTF-8"));
	        request.addHeader(new HTTPHeader("Content-Type", "multipart/form-data;boundary=" + BOUNDARY));
	        
	        BOUNDARY = "--" + BOUNDARY;
	        

	        
	        StringBuffer sb = new StringBuffer();
	      //写文本url参数
	        HashMap<String, String> textParams = new HashMap<String, String>();
	        //textParams.put("access_token", req.getParameter("token"));
	        textParams.put("status", weiboText);
	        writeStringParams(sb,textParams);
	        
	        //写图片文件
	        sb.append(BOUNDARY + "\r\n");

				
			sb.append("Content-Disposition: form-data; name=\"pic\";filename=\"pic" + req.getParameter("asin") + ".jpg\" \r\n");
	        sb.append("Content-Type:" + picContentType + "\r\n\r\n");
	        
	        
	        //结尾
	        String end_data = "\r\n" + BOUNDARY + "--\r\n"; 
	        
	        //计算长度
	        request.addHeader(new HTTPHeader("Content-Length", String.valueOf(sb.toString().getBytes().length + file.length + ("\r\n" + end_data).getBytes().length)));
	        ByteArrayOutputStream os = new ByteArrayOutputStream();
            DataOutputStream out = new DataOutputStream(os);
            out.writeBytes(sb.toString());
	        out.write(file);
	        out.writeBytes("\r\n");
	        out.writeBytes(end_data);
	        out.flush();
	        out.close();
	        request.setPayload(os.toByteArray());
	        
	        URLFetchService service = URLFetchServiceFactory.getURLFetchService();
	        
	        
	        HTTPResponse r = service.fetch(request);
	        Map<String, String> headers = new HashMap<String, String>();
            for (HTTPHeader h : r.getHeaders()) {
                headers.put(h.getName(), h.getValue());
            }
            byte[] content = r.getContent();
            InputStream is = new ByteArrayInputStream(content);
            if ("gzip".equals(headers.get("Content-Encoding"))) {
                // the response is gzipped
                try {
                    is = new GZIPInputStream(is);
                } catch (IOException e) {
                    
                }
            }
            
            StringWriter writer = new StringWriter();
	        IOUtils.copy(is, writer);
	        log.info(writer.toString());
	        try {
				Thread.sleep(30000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			resp.setStatus(200);
		}else{
			resp.setStatus(400);
		}
	}
	
	//普通字符串数据  
    private void writeStringParams(StringBuffer sb, HashMap<String, String> textParams) throws IOException {  
    	
        Set<String> keySet = textParams.keySet();  
        for (Iterator<String> it = keySet.iterator(); it.hasNext();) {  
        	sb.append(BOUNDARY + "\r\n");
            String name = it.next();  
            String value = textParams.get(name);  
            sb.append("Content-Disposition: form-data; name=\"" + name + "\"\r\n");  
            sb.append("Content-Type: text/plain; charset=UTF-8\r\n\r\n");
//            if (!name.equals("access_token")){
//            	sb.append(URLEncoder.encode(value,"UTF-8") + "\r\n");
//            }else{
            	sb.append(value + "\r\n");
//            }
            //sb.append("\r\n");  
        }  
    }  
}
